<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <el-dialog class="add_skin_library" v-model="props.addVisible" :title="modalType === 'edit' ? '修改铺层' : '新增铺层'"
    @close="handleVisible('cancel')">
    <el-form ref="formRef" size="small" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="铺层代码" prop="plyCode">
        <el-input placeholder="请输入" v-model="formData.plyCode" />
      </el-form-item>
      <el-form-item label="材料" prop="material">
        <el-select v-model="formData.material" placeholder="请选择">
          <el-option v-for="item in materialData" :key="item.value" :value="item.value" :label="item.label">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="单层厚度" prop="thickness">
        <el-input placeholder="请输入" v-model="formData.thickness" />
      </el-form-item>
      <el-form-item label="是否对称铺层" prop="symmetrical">
        <el-radio-group v-model="formData.symmetrical">
          <el-radio value="1" size="small">是</el-radio>
          <el-radio value="0" size="small">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="PLY1">
        <div class="ply_div">
          <el-input class="ply_input1" placeholder="请输入" v-model="formData.PLY1.value" />
          <el-input class="ply_input" disabled v-if="formData.PLY1?.custom?.material"
            :value="`${formData.PLY1?.custom?.material}-${formData.PLY1?.custom?.thickness}`">
            <template #append>
              <el-button icon="Delete" @click="deleteCus('PLY1')" />
            </template>
          </el-input>
          <a class="ply_a" v-else @click="addCus('PLY1')">自定义材料和厚度</a>
        </div>
      </el-form-item>
      <el-form-item :label="item.label" :key="item.label" v-for="(item, index) in plys">
        <div class="ply_item">
          <el-input class="ply_input1" v-model="formData[item.label].value" placeholder="请输入" />
          <el-input class="ply_input" disabled v-if="formData[item.label]?.custom?.material"
            :value="`${formData[item.label]?.custom?.material}-${formData[item.label]?.custom?.thickness}`">
            <template #append>
              <el-button icon="Delete" @click="deleteCus(item.label)" />
            </template>
          </el-input>
          <a class="ply_a" v-else @click="addCus(item.label)">自定义材料和厚度</a>
          <el-icon class="ply_icon" @click="removeItem(item)" v-if="index === plys.length - 1">
            <Remove />
          </el-icon>
        </div>
      </el-form-item>
      <el-form-item style="width: 100%">
        <el-button style="width: 100%" type="primary" plain icon="Plus" @click="addPly">添加</el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button size="small" @click="handleVisible('cancel')">取消</el-button>
        <el-button size="small" type="primary" @click="submitAdd"> 确认 </el-button>
      </div>
    </template>
    <SkinCustomerAdd :visible="customerAddVisible" :row-data="currentData" v-if="customerAddVisible"
      @handleEvent="handleEvent" />
  </el-dialog>
</template>
<script name="addSkinLibrary" setup>
import SkinCustomerAdd from './SkinCustomerAdd.vue';
import { saveLayer } from '@/api/layerLibrary';
import { materialList } from '@/api/layupLibrary';
const props = defineProps(['addVisible', 'rowData']);
const emit = defineEmits(['handleEvent']);
const modalType = props?.rowData ? 'edit' : 'add';
const formRef = ref(null);
const customerAddVisible = ref(false);
const formData = ref({
  plyCode: '',
  material: '',
  thickness: '',
  symmetrical: '',
  PLY1: { value: "", custom: { material: "", thickness: "" } }
});
const plys = ref([]);
const currentData = ref(null);
const materialData = ref([]);


const rules = ref({
  plyCode: [{ required: true, message: '铺层代码不能为空', trigger: 'blur' }],
  material: [{ required: true, message: '材料不能为空', trigger: 'blur' }],
  thickness: [{ required: true, message: '单层厚度不能为空', trigger: 'blur' }],
  symmetrical: [{ required: true, message: '请选择是否对称铺层', trigger: 'blur' }]
});
const addCus = (data) => {
  customerAddVisible.value = true;
  currentData.value = data;
};
// 新增ply
const addPly = () => {
  const length = plys.value.length;
  plys.value.push({ label: `PLY${length + 2}`, value: `PLY${length + 2}` });
  formData.value[`PLY${length + 2}`] = { value: '', custom: { material: '', thickness: '' } };
};
// 删除ply
const removeItem = (data) => {
  // filter不具备响应式
  const resultArr = plys.value.filter((item) => item.label !== data.label);
  plys.value = resultArr;
  delete formData.value[data.label];
};
const handleVisible = (type) => {
  if (type === 'cancel') {
    emit('handleEvent', { type: 'close' });
  } else {
    emit('handleEvent', { type: 'refresh' });
  }
};
const deleteCus = (data) => {
  if (formData.value[data]?.custom) {
    formData.value[data].custom = { material: '', thickness: '' };
  }
};
const handleEvent = (data) => {
  console.log(data)
  if (data?.type === 'cancel') {
    customerAddVisible.value = false;
  } else if (data?.type === 'refresh') {
    customerAddVisible.value = false;
    console.log(formData.value)
    if (currentData.value) {
      const obj = { material: data.data.material, thickness: data.data.thickness };
      formData.value[currentData.value].custom = obj;
    }
  }
};
const submitAdd = () => {
  formRef.value.validate((valid) => {
    if (!valid) {
      return false;
    }
    //处理数据
    let plyData = {};
    plyData.PLY1 = formData.value.PLY1; // 添加PLY1
    if(!formData.value.PLY1?.custom?.material) {
      plyData.PLY1.custom = null;
    } 
    plys.value.forEach((el) => {
      const obj = {};
      obj[el.label] = formData.value[el.label];
      if (!obj[el.label]?.custom?.material) {
        obj[el.label].custom = null; // 如果没有自定义材料，则设置为null
      }
      plyData[el.label] = obj[el.label];
    });
    formData.value.plyData = plyData;
    if (modalType === 'edit') {
      formData.value.materialId = props?.rowData?.isfdLayupEquivalentMaterialVo?.id;
    }
    saveLayer(formData.value).then((res) => {
      if (res) {
        if (modalType === 'add') {
          ElMessage({ showClose: true, message: '新增成功。', type: 'success' });
        } else {
          ElMessage({ showClose: true, message: '修改成功。', type: 'success' });
        }
        handleVisible();
      }
    });
  });
};
onMounted(() => {
  materialList({ materialName: '', materialNumber: '', pageNum: 1, pageSize: 9999 }).then((res) => {
    if (res.code === 200) {
      console.log('MATERIAL', res);
      materialData.value = res.rows.map((item) => {
        return { label: item.materialName, value: item.materialNumber };
      });
      console.log('materialData.value', materialData.value);
    }
  });
  if (modalType === 'edit') {
  formData.value = props.rowData;
  formData.value.symmetrical = props.rowData?.symmetrical?.toString();

  if (props.rowData?.data) {
    const dataArr = JSON.parse(props.rowData?.data);
    // 遍历dataArr所有的key
    const keys = Object.keys(dataArr);
    keys.forEach((key, index) => {
      if (!formData.value[key]) {
        formData.value[key] = { value: "", custom: { material: "", thickness: "" } };
      }
      formData.value[key].value = dataArr[key]?.value || '';
      formData.value[key].custom = dataArr[key]?.custom || { material: '', thickness: '' };
      if(index!=0) {
        plys.value.push({ label: `PLY${index + 1}`, value: `PLY${index + 1}` });
      } 
      
    });
    console.log("formData.value", formData.value);
  }
}
});
</script>
<style lang="scss" scoped>
.add_skin_library {
  user-select: none;

  .ply_item {
    width: 100%;
    display: flex;
    align-items: center;

    .ply_icon {
      font-size: 16px;
      margin-left: 10px;
      cursor: pointer;
    }

    .ply_input1 {
      width: 60%;
      margin-right: 10px;
    }

    .ply_input {
      width: 30%;
      margin-right: 10px;
    }

    .ply_a {
      color: #409eff;
      cursor: pointer;
      text-decoration: underline;
    }
  }

  .ply_div {
    display: flex;
    width: 100%;

    .ply_input1 {
      width: 60%;
      margin-right: 10px;
    }

    .ply_input {
      width: 30%;
      margin-right: 10px;
    }

    .ply_a {
      color: #409eff;
      cursor: pointer;
      text-decoration: underline;
    }
  }
}
</style>
